#include "eeprom.h"
#include "ioi2c.h"
#include "utility.h"
#include <stdio.h>
#include "stm32f4xx_hal.h"
extern I2C_HandleTypeDef hi2c1;

uint8_t AA24x_ReadOneByte(uint16_t addr, HAL_StatusTypeDef *ret)
{
	uint8_t tmp[3]; 
	*ret = HAL_I2C_Mem_Read(&hi2c1, 0xa0, addr,I2C_MEMADD_SIZE_16BIT, tmp, 1, 200);
  return tmp[0]; 
}

void AA24x_WriteOneByte(uint16_t addr,uint8_t dt, HAL_StatusTypeDef *ret)
{
	*ret = HAL_I2C_Mem_Write(&hi2c1,0xa0,addr,I2C_MEMADD_SIZE_16BIT, &dt,1,200);
	while (*ret == HAL_OK && HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY)
	{
		
	}

	/* Check if the EEPROM is ready for a new operation */
	while (*ret == HAL_OK && HAL_I2C_IsDeviceReady(&hi2c1, 0xa0, 1000, 200) == HAL_TIMEOUT);

	/* Wait for the end of the transfer */
	while (*ret == HAL_OK && HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY)
	{
		
	}
}

//addr需要安32对齐
void AA24x_WriteBytes(uint16_t addr, uint8_t *dt, uint16_t length, HAL_StatusTypeDef *ret) {
	
	uint16_t curAddr = addr;
	uint16_t endAddr = addr+length;
	uint16_t remain = length;
	uint8_t *p = dt;
	for(;curAddr<endAddr;curAddr+=32) {
		uint8_t tmp[32]; 
		uint16_t len = remain>32?32:remain;
		for(int i=0;i<len;i++) {
			tmp[i] = *(p+i);
		}
		*ret = HAL_I2C_Mem_Write(&hi2c1,0xa0,curAddr,I2C_MEMADD_SIZE_16BIT, tmp,len,1000);
		while (*ret == HAL_OK && HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY)
		{
			
		}

		/* Check if the EEPROM is ready for a new operation */
		while (*ret == HAL_OK && HAL_I2C_IsDeviceReady(&hi2c1, 0xa0, 1000, 1000) == HAL_TIMEOUT);

		/* Wait for the end of the transfer */
		while (*ret == HAL_OK && HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY)
		{
			
		}
		p+=len;
		remain-=len;
	}
}

uint8_t AA24x_Test(void)
{
	uint8_t tmp[10];
	uint8_t ret = 1;
	HAL_StatusTypeDef error;
	for(int i=0;i<10;i++)
	{
		tmp[i] = AA24x_ReadOneByte(i, &error);
		if(error != HAL_OK)
			break;
		AA24x_WriteOneByte(i,i, &error);
		if(error != HAL_OK)
			break;
	}
	delay_ms(10);
	if(error == HAL_OK)
	{
		for(int i=0;i<10;i++)
		{
			int rd = AA24x_ReadOneByte(i, &error);
			AA24x_WriteOneByte(i,tmp[i], &error);
			if(rd != i)
			{
				ret = 0;
				break;
			}
		}
	}
	if(ret == 0 || error != HAL_OK)
	{
		ret = 0;
		printf("eeprom test failed.\n");
	}
	return ret;
}
